package Pet.Management.controller;

import Pet.Management.domain.entity.ChatMessage;
import Pet.Management.repository.ChatMessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/chat")
public class ChatController {

    @Autowired
    private ChatMessageRepository chatMessageRepository;

    /**
     * 获取聊天记录
     */
    @GetMapping("/messages/{userId}")
    public ResponseEntity<Map<String, Object>> getChatMessages(
            @PathVariable Long userId,
            @RequestParam(required = false) Long adminId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {

        Pageable pageable = PageRequest.of(page, size);
        Page<ChatMessage> messagePage;

        if (adminId != null) {
            // 获取特定用户和管理员之间的对话
            messagePage = chatMessageRepository.findConversation(userId, adminId, pageable);
        } else {
            // 获取用户的所有聊天记录
            messagePage = chatMessageRepository.findByUserIdOrderByCreateTimeDesc(userId, pageable);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("messages", messagePage.getContent());
        response.put("currentPage", messagePage.getNumber());
        response.put("totalItems", messagePage.getTotalElements());
        response.put("totalPages", messagePage.getTotalPages());

        return ResponseEntity.ok(response);
    }

    /**
     * 发送消息
     */
    @PostMapping("/send")
    public ResponseEntity<ChatMessage> sendMessage(@RequestBody ChatMessage message) {
        message.setCreateTime(java.time.LocalDateTime.now());
        message.setIsRead(false);
        ChatMessage savedMessage = chatMessageRepository.save(message);
        return ResponseEntity.ok(savedMessage);
    }

    /**
     * 标记消息为已读
     */
    @PutMapping("/messages/{messageId}/read")
    @Transactional
    public ResponseEntity<Void> markMessageAsRead(@PathVariable Long messageId) {
        chatMessageRepository.markAsRead(messageId);
        return ResponseEntity.ok().build();
    }

    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread-count")
    public ResponseEntity<Map<String, Long>> getUnreadCount(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) Long adminId) {

        Map<String, Long> response = new HashMap<>();
        
        if (userId != null) {
            response.put("userUnreadCount", 
                chatMessageRepository.countByUserIdAndIsRead(userId, false));
        }
        
        if (adminId != null) {
            response.put("adminUnreadCount", 
                chatMessageRepository.countByAdminIdAndIsRead(adminId, false));
        }

        return ResponseEntity.ok(response);
    }

    /**
     * 获取管理员的所有聊天记录
     */
    @GetMapping("/admin/messages/{adminId}")
    public ResponseEntity<Map<String, Object>> getAdminChatMessages(
            @PathVariable Long adminId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {

        Pageable pageable = PageRequest.of(page, size);
        Page<ChatMessage> messagePage = chatMessageRepository.findByAdminIdOrderByCreateTimeDesc(adminId, pageable);

        Map<String, Object> response = new HashMap<>();
        response.put("messages", messagePage.getContent());
        response.put("currentPage", messagePage.getNumber());
        response.put("totalItems", messagePage.getTotalElements());
        response.put("totalPages", messagePage.getTotalPages());

        return ResponseEntity.ok(response);
    }
} 